/***************************************************************
*  Copyright (c) 2007 by GroupMe! Team (www.groupme.net)
*  All rights reserved.
*
*  This file is part of the GroupMe! Project. Source code of 
*  this project is closed and redistribution of this code is
*  prohibited. 
*  
*  Contact: http://www.groupme.net
*
*  This copyright notice MUST APPEAR in all copies of the file!
***************************************************************/
package net.groupme.utils.sql;

import java.sql.Types;

import javax.sql.DataSource;

import net.groupme.exceptions.UpdateFailedException;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.SqlUpdate;

/**
 * created on Jun 28, 2007
 * 
 * This class provides some utility methods for updating certain
 * datasets...
 * 
 * @author Fabian Abel, <a href="mailto:abel@l3s.de">abel@l3s.de</a>
 * @author last edited by: $Author: fabian $
 * 
 * @version $Revision: 1.2 $ $Date: 2007-06-28 10:25:06 $
 */
public class SQLUpdateUtility {

	/**
	 * Updates a the value of given field which belongs to the data row which has the given id.
	 * 
	 * @param ds the {@link DataSource} on which the query should be executed
	 * @param table the table in which a field should be updated
	 * @param idFieldName the name of the ID column of the table (common would be <i>id</i>).
	 * @param id the id of the data set
	 * @param fieldToUpdate the name of the field to update
	 * @param value the new value (String)
	 * @param datatype the datatype of the new value (one of the integers defined in {@link Types}.
	 * @throws UpdateFailedException thrown if the update failed
	 */
	public static final void updateSingleFieldByID(DataSource ds, String table, 
			String idFieldName, String id, String fieldToUpdate, String value, int datatype) throws UpdateFailedException{
		SqlUpdate su = new SqlUpdate(
				ds,
				"UPDATE " + table + " SET " + fieldToUpdate + " = ? WHERE " + idFieldName + " = ?"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
		su.declareParameter(new SqlParameter(fieldToUpdate, datatype)); //$NON-NLS-1$
		su.declareParameter(new SqlParameter(idFieldName, Types.INTEGER)); //$NON-NLS-1$
		su.compile();
		Object[] values = {value, new Integer(id)};
		int count = su.update(values);
		if (count == 0){
			throw new UpdateFailedException("Failed to update the field '" + fieldToUpdate + "' in table '" + table + "' with the given value '" + value + "'");
		}
	}
}
